package com.tianhui.consignortwofei.mvp.ui.activity.deliverGoods.normal;

import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.fgs.common.CommonFragment;
import com.fgs.common.CommonPresenter;
import com.fgs.common.CommonResponse;
import com.fgs.common.CommonView;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;
import com.fgs.common.utils.DateUtil;
import com.fgs.common.widget.SelectDialog;
import com.fgs.common.widget.TabSwitchView;
import com.fgs.common.widget.itemView.ClickItemView;
import com.fgs.common.widget.itemView.InputItemView;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.manager.SharedPreferenceManager;
import com.tianhui.consignortwofei.mvp.model.DriverModel;
import com.tianhui.consignortwofei.mvp.model.InsureModel;
import com.tianhui.consignortwofei.mvp.model.OrderModel;
import com.tianhui.consignortwofei.mvp.model.enty.DictionaryInfo;
import com.tianhui.consignortwofei.mvp.model.enty.DriverInfo;
import com.tianhui.consignortwofei.mvp.model.enty.insure.InsureTypeInfo;
import com.xuexiang.xutil.common.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author fgs
 * @date 2020/9/1
 * @description
 **/
public class DeliverGoodsStepFourActivity extends DeliverGoodsActivity {

    @BindView(R.id.activity_deliver_goods_step_four_goodsPriceInputItemView)
    protected InputItemView mGoodsPriceInputItemView;
    @BindView(R.id.activity_deliver_goods_step_four_consignorInputItemView)
    protected InputItemView mConsignorInputItemView;
    @BindView(R.id.activity_deliver_goods_step_four_consignorPhoneInputItemView)
    protected InputItemView mConsignorPhoneInputItemView;
    @BindView(R.id.activity_deliver_goods_step_four_insureAmountInputItemView)
    protected InputItemView mInsureAmountInputItemView;

    @BindView(R.id.activity_deliver_goods_step_three_sendObjectClickItemView)
    protected ClickItemView mSendObjectClickItemView;
    @BindView(R.id.activity_deliver_goods_step_four_objectDetailLinearLayout)
    protected LinearLayout mObjectDetailLinearLayout;
    @BindView(R.id.activity_deliver_goods_step_four_driverPhoneInputItemView)
    protected InputItemView mDriverPhoneInputItemView;
    @BindView(R.id.activity_deliver_goods_step_four_driverDetailLinearLayout)
    protected LinearLayout mDriverDetailLinearLayout;
    @BindView(R.id.activity_deliver_goods_step_four_driverNameTextView)
    protected TextView mDriverNameTextView;
    @BindView(R.id.activity_deliver_goods_step_four_driverPhoneTextView)
    protected TextView mDriverPhoneTextView;
    @BindView(R.id.activity_deliver_goods_step_four_vehicleNumberTextView)
    protected TextView mVehicleNumberTextView;


    @BindView(R.id.activity_deliver_goods_step_three_insureTypeClickItemView)
    protected ClickItemView mInsureTypeClickItemView;

    @BindView(R.id.activity_deliver_goods_step_four_pushableTabSwitchView)
    protected TabSwitchView mPushableTabSwitchView;
    @BindView(R.id.activity_deliver_goods_step_four_transportModeTabSwitchView)
    protected TabSwitchView mTransportModeTabSwitchView;
    @BindView(R.id.activity_deliver_goods_step_four_insureLinearLayout)
    protected LinearLayout mInsureLinearLayout;
    @BindView(R.id.activity_deliver_goods_step_four_insureTabSwitchView)
    protected TabSwitchView mInsureTabSwitchView;

    @BindView(R.id.activity_deliver_goods_step_four_roadTypeTabSwitchView)
    protected TabSwitchView mRoadTypeTabSwitchView;
    @BindView(R.id.activity_deliver_goods_step_four_roadTypeInputItemView)
    protected InputItemView mRoadTypeInputItemView;

    private SelectDialog mSendObjectSelectDialog;
    private SelectDialog mInsureTypeSelectDialog;
    //0定额1定率
    private int roadType = 0;
    private int mMaxInsure;
    private int mMinInsure;

    private DriverModel driverModel;

    @Override
    public int getLayoutId() {
        return R.layout.activity_deliver_goods_step_four;
    }

    @Override
    public CommonPresenter createPresenter() {
        return null;
    }

    @Override
    public CommonView createView() {
        return null;
    }

    @Override
    public void initData() {
        mGoodsInfo.isstate = 1;
        mGoodsInfo.isdelegateshipment = "1";
//        mGoodsInfo.Isinsure = "1";
        mGoodsInfo.isinsure = "1";
        mGoodsInfo.ispush = "0";
        mGoodsInfo.billsource = "2";
        mGoodsInfo.sentto = "00";
        mGoodsInfo.consumequota = "";
        mGoodsInfo.consumefixedrate = "";
    }

    @Override
    public void initView() {
        mConsignorInputItemView.setContent(SharedPreferenceManager.getInstance().getConsignorName());
        mConsignorPhoneInputItemView.setContent(SharedPreferenceManager.getInstance().getPhone());
        mSendObjectClickItemView.setContent("全部");
        showStepFourStatus();
    }

    private void requestInsureType() {
        new InsureModel().insureTypeListModel(this, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<List<InsureTypeInfo>>>() {
            @Override
            public void onNext(CommonResponse<List<InsureTypeInfo>> commonResponse) {
                if (!isFinishing() && !isDestroyed()) {
                    if (commonResponse.getCode() == 20000) {
                        List<InsureTypeInfo> insureTypeInfoList = commonResponse.getData();
                        if (insureTypeInfoList != null && insureTypeInfoList.size() > 0) {
                            showInsureTypeInfoDialog(insureTypeInfoList);
                        } else {
                            showToast("未获取到投保类型信息");
                        }
                    } else {
                        showToast(commonResponse.getMsg());
                    }
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });
    }

    private void showInsureTypeInfoDialog(List<InsureTypeInfo> insureTypeInfoList) {
        mInsureTypeSelectDialog = new SelectDialog<InsureTypeInfo>(this);
        mInsureTypeSelectDialog.setTitle("请选择投保类型");
        mInsureTypeSelectDialog.setList(insureTypeInfoList);
        mInsureTypeSelectDialog.show();
        mInsureTypeSelectDialog.setOnSelectItemClickLister(new SelectDialog.OnSelectItemClickListener<InsureTypeInfo>() {
            @Override
            public void onItemClick(InsureTypeInfo item, int position) {
                mInsureTypeClickItemView.setContent(item.getSelectItemText());
//                mInsureAmountInputItemView.setContent((item.minAmount / 10000) + "");
                mMaxInsure = item.maxAmount;
                mMinInsure = item.minPremium;
                mGoodsInfo.schemeCode = item.schemeCode;

            }
        });
    }

    @Override
    public void initListener() {
        //是否推送
        mPushableTabSwitchView.setOnTabCheckedChangeListener(new TabSwitchView.OnTabCheckedChangeListener() {
            @Override
            public void onCheckedChanged(int position, String item, String value) {
                mGoodsInfo.ispush = value;
            }
        });
        //运输方式
        mTransportModeTabSwitchView.setOnTabCheckedChangeListener(new TabSwitchView.OnTabCheckedChangeListener() {
            @Override
            public void onCheckedChanged(int position, String item, String value) {

                mGoodsInfo.isdelegateshipment = value;
            }
        });
        //是否投保
        mInsureTabSwitchView.setOnTabCheckedChangeListener(new TabSwitchView.OnTabCheckedChangeListener() {
            @Override
            public void onCheckedChanged(int position, String item, String value) {
                if (position == 0) {
                    mInsureLinearLayout.setVisibility(View.VISIBLE);
                    mInsureAmountInputItemView.setContent("0");
                } else {
                    mInsureLinearLayout.setVisibility(View.GONE);
                    mInsureAmountInputItemView.setContent("");
                }
//                mGoodsInfo.Isinsure = value;
                mGoodsInfo.isinsure = value;

            }
        });

        //路耗类型
        mRoadTypeTabSwitchView.setOnTabCheckedChangeListener(new TabSwitchView.OnTabCheckedChangeListener() {
            @Override
            public void onCheckedChanged(int position, String item, String value) {
                if (position == 1) {
                    mRoadTypeInputItemView.setTitle("路耗计量（‰/车）");
                } else {
                    mRoadTypeInputItemView.setTitle("路耗计量（kg/车）");
                }
                roadType = position;
            }
        });

        mGoodsPriceInputItemView.setOnInputItemListener(new InputItemView.OnInputItemListener() {
            @Override
            public void onInput(String string) {
                mInsureAmountInputItemView.setContent(getInsurePrice(string, mGoodsInfo.weight));
            }
        });

    }

    @Override
    public CommonFragment createFragment() {
        return null;
    }

    @OnClick(R.id.activity_deliver_goods_step_three_sendObjectClickItemView)
    public void sendObject() {
        if (mSendObjectSelectDialog == null) {
            requestSentObject();
        } else {
            mSendObjectSelectDialog.show();
        }
    }

    private void requestSentObject() {
        Map<String, String> map = new HashMap<>();
        map.put("pid", "2759");
        new OrderModel().dictionaryModel(this, map, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<List<DictionaryInfo>>>() {
            @Override
            public void onNext(CommonResponse<List<DictionaryInfo>> commonResponse) {
                if (!isFinishing() && !isDestroyed()) {
                    if (commonResponse.getCode() == 20000) {
                        List<DictionaryInfo> list = commonResponse.getData();
                        if (list != null && list.size() > 0) {
                            showSendObjectDialog(list);
                        } else {
                            showToast("未获取到发送对象信息");
                        }
                    } else {
                        showToast(commonResponse.getMsg());
                    }
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {

                showToast(e.message);
            }
        });
    }

    private void showSendObjectDialog(List<DictionaryInfo> list) {
        mSendObjectSelectDialog = new SelectDialog<String>(this);
        mSendObjectSelectDialog.setTitle("请选择发送对象");
        mSendObjectSelectDialog.setList(list);
        mSendObjectSelectDialog.show();
        mSendObjectSelectDialog.setOnSelectItemClickLister(new SelectDialog.OnSelectItemClickListener<DictionaryInfo>() {
            @Override
            public void onItemClick(DictionaryInfo item, int position) {
                mSendObjectClickItemView.setContent(item.getSelectItemText());
                mGoodsInfo.sentto = item.getSelectItemTextValue();
                if (position == 2) {
                    mObjectDetailLinearLayout.setVisibility(View.VISIBLE);
                } else {
                    mObjectDetailLinearLayout.setVisibility(View.GONE);
                }
            }
        });
    }

    @OnClick(R.id.activity_deliver_goods_step_three_insureTypeClickItemView)
    public void insureType() {
        if (mInsureTypeSelectDialog == null) {
            requestInsureType();
        } else {
            mInsureTypeSelectDialog.show();
        }
    }

    @OnClick(R.id.activity_deliver_goods_step_four_commitButton)
    public void commit() {
        String consignor = mConsignorInputItemView.getContent();
        String consignorPhone = mConsignorPhoneInputItemView.getContent();
        String goodsPrice = mGoodsPriceInputItemView.getContent();
        String insureAmount = mInsureAmountInputItemView.getContent();
        String roadTypeValue = mRoadTypeInputItemView.getContent();
        String driverPhone = mDriverPhoneInputItemView.getContent();
        if (roadType == 0) {
            mGoodsInfo.consumequota = roadTypeValue;
            mGoodsInfo.consumefixedrate = "";
        } else {
            mGoodsInfo.consumequota = "";
            mGoodsInfo.consumefixedrate = roadTypeValue;
        }

        mGoodsInfo.clientperson = consignor;
        mGoodsInfo.clienttel = consignorPhone;
        mGoodsInfo.goodsunitprice = goodsPrice;

        mGoodsInfo.sendordertime = DateUtil.getStandardTime(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");

        if (TextUtils.isEmpty(mGoodsInfo.goodsunitprice)) {
            showToast("请填写货物单价");
            return;
        }
        if (TextUtils.isEmpty(mGoodsInfo.clienttel)) {
            showToast("委托人电话不能为空");
            return;
        }

        if (!TextUtils.isEmpty(mGoodsInfo.sentto) && mGoodsInfo.sentto.equals("02")) {
            if (TextUtils.isEmpty(driverPhone)) {
                showToast("发送对象明细不能为空");
                return;
            }
            mGoodsInfo.senttodetails = driverPhone;
        } else {
            mGoodsInfo.senttodetails = "";
        }

        if (mGoodsInfo.isinsure.equals("1")) {

            if (TextUtils.isEmpty(mGoodsInfo.schemeCode)) {
                showToast("请选择投保类型");
                return;
            }
            if (TextUtils.isEmpty(insureAmount)) {
                showToast("请输入投保金额");
                return;
            }
            //投保金额 = 货物重量*货物单价（保额必需是10000的整数倍，且在保额范围内，10002按20000处理）

            int insurePrice = StringUtils.toInt(insureAmount);
            if (insurePrice > mMaxInsure || insurePrice < mMinInsure) {
                showToast("投保金额不在投保类型的保额范围内");
                return;
            }
            mGoodsInfo.insureprice = StringUtils.toInt(insureAmount) * 10000 + "";
        } else {
            mGoodsInfo.insureprice = "";
            mGoodsInfo.schemeCode = "";
        }

        requestPublishSource();

    }



    private String getInsurePrice(String goodsPrice, String goodsWeight) {
        String insurePrice = "";
        if (!TextUtils.isEmpty(goodsPrice) && !TextUtils.isEmpty(goodsWeight)) {
            insurePrice = (int) Math.ceil((StringUtils.toDouble(goodsWeight) * StringUtils.toDouble(goodsPrice)) / 10000) + "";
            return insurePrice;
        }
        return "";
    }

    @OnClick(R.id.activity_deliver_goods_step_four_driverDetailTextView)
    public void checkDriverDetail() {
        String driverPhone = mDriverPhoneInputItemView.getContent();
        if (!TextUtils.isEmpty(driverPhone)) {
            requestDriverList(driverPhone);
        } else {
            showToast("请输入手机号");
        }
    }

    public void requestDriverList(String phone) {
        if (TextUtils.isEmpty(phone)) return;
        Map<String, String> map = new HashMap<>();
        map.put("drivertel", phone);
//        map.put("page", "1");
//        map.put("offset", "0");
//        map.put("limit", "10");
        if (driverModel == null) {
            driverModel = new DriverModel();
        }
        driverModel.assignDriverListModel(this, map, true, bindLifecycle(), new ObserverResponseListener<CommonResponse<List<DriverInfo>>>() {
            @Override
            public void onNext(CommonResponse<List<DriverInfo>> commonResponse) {
                if (!isFinishing() && !isDestroyed()) {
                    if (commonResponse.getCode() == 20000) {
                        List<DriverInfo> list = commonResponse.getData();
                        if (list != null && list.size() > 0) {
                            for (DriverInfo info : list) {
                                if (info.drivertel.equals(phone)) {
                                    showDriverInfoView(info);
                                }
                            }

                        } else {
                            showToast("未找到司机信息");
                            hideDriverInfoView();
                        }

                    } else {
                        hideDriverInfoView();
                        showToast(commonResponse.getMsg());
                    }
                }
            }


            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
                hideDriverInfoView();
            }
        });
    }

    private void showDriverInfoView(DriverInfo info) {
        mDriverDetailLinearLayout.setVisibility(View.VISIBLE);
        mDriverNameTextView.setText(info.drivername);
        mDriverPhoneTextView.setText(info.drivertel);
        mVehicleNumberTextView.setText(info.defaultvehiclenum);
    }

    private void hideDriverInfoView() {
        mDriverDetailLinearLayout.setVisibility(View.GONE);
    }
}
